const app = getApp()

Page({
  data: {
    flashSales: [],
    statusBarHeight: 0,
    navbarHeight: 0
  },

  onLoad() {
    // 获取系统信息，用于适配状态栏高度
    const systemInfo = wx.getSystemInfoSync()
    const statusBarHeight = systemInfo.statusBarHeight || 0
    // 导航栏总高度 = 状态栏高度 + 88rpx (导航栏内容高度，约44px)
    const navbarHeight = statusBarHeight + 44
    this.setData({
      statusBarHeight: statusBarHeight,
      navbarHeight: navbarHeight
    })
    this.loadFlashSales()
  },

  onShow() {
    this.loadFlashSales()
  },

  loadFlashSales() {
    const flashSales = wx.getStorageSync('flashSales') || this.getMockFlashSales()
    
    this.setData({
      flashSales: flashSales.map(item => ({
        ...item,
        formattedPrice: item.price.toFixed(2),
        formattedOriginalPrice: item.originalPrice.toFixed(2),
        orderTime: this.formatTime(item.orderTime)
      }))
    })
  },

  getMockFlashSales() {
    return [
      {
        id: 1,
        productId: 1,
        productTitle: '毕业趣旅行-高星好评-四日解锁京城-360度探秘皇家宫殿',
        productImage: '',
        price: 1,
        originalPrice: 400,
        orderNo: 'FS20240619001',
        orderTime: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString(),
        status: 'success' // success-成功, pending-待支付
      },
      {
        id: 2,
        productId: 2,
        productTitle: '水舞间水上汇演门票',
        productImage: '',
        price: 99,
        originalPrice: 367,
        orderNo: 'FS20240620002',
        orderTime: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000).toISOString(),
        status: 'pending'
      }
    ]
  },

  formatTime(timeStr) {
    const date = new Date(timeStr)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}`
  },

  goToProductDetail(e) {
    const productId = e.currentTarget.dataset.productId
    wx.navigateTo({
      url: `/pages/product-detail/product-detail?id=${productId}`
    })
  },

  goToOrderDetail(e) {
    const orderNo = e.currentTarget.dataset.orderNo
    wx.navigateTo({
      url: `/pages/order-detail/order-detail?orderNo=${orderNo}`
    })
  },

  payOrder(e) {
    const orderNo = e.currentTarget.dataset.orderNo
    wx.showToast({
      title: '跳转支付',
      icon: 'none'
    })
    // 实际项目中跳转到支付页面
    // wx.navigateTo({
    //   url: `/pages/payment/payment?orderNo=${orderNo}`
    // })
  },

  goBack() {
    wx.navigateBack()
  }
})

